package com.hsy.crm.web.service.impl;

import com.hsy.crm.web.domain.cm.App;
import com.hsy.crm.web.domain.cm.Unified;
import com.hsy.crm.web.domain.entity.Company;
import com.hsy.crm.web.domain.entity.User;
import com.hsy.crm.web.domain.ex.ServiceException;
import com.hsy.crm.web.domain.po.company.CompanyPagePo;
import com.hsy.crm.web.domain.vo.company.CompanyPageVo;
import com.hsy.crm.web.mapper.CompanyMapper;
import com.hsy.crm.web.mapper.UserMapper;
import com.hsy.crm.web.service.base.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CompanyService extends BaseService<Company> {

    @Autowired
    CompanyMapper companyMapper;

    @Autowired
    UserMapper userMapper;

    public Unified<List<CompanyPagePo>> find(CompanyPageVo companyPageVo) {
        return Unified.newInstance(companyMapper.find(companyPageVo));
    }

    public Unified<Integer> insertCompany(Company company) {
        Company select = new Company();
        select.setCustomerId(company.getCustomerId());
        select.setName(company.getName());
        int count = companyMapper.selectCount(select);
        if( count > 0 ){
            throw new ServiceException(App.BussError.NAME_REPEAT.getCode());
        }

        return Unified.newInstance(companyMapper.insertCompany(company));
    }

    @Transactional
    public Unified<Integer> deleteCompany(Company company) {

        Unified<Integer> unified = Unified.create(Integer.class);
        if( hasChildren(company) ){
            unified.setResult(App.BussError.COMPANY_DELETE_1.getCode());
            return unified;
        }

        if(hasUser(company)){
            unified.setResult(App.BussError.COMPANY_DELETE_2.getCode());
            return unified;
        }

        this.delete(company);
        return unified;
    }

    public Unified<Integer> updateCompany(Company company) {

        Integer count = companyMapper.updateSelect(company);
        if( count != null ){
            throw new ServiceException(App.BussError.NAME_REPEAT.getCode());
        }

        return Unified.newInstance(this.update(company));
    }

    private boolean hasChildren(Company company){
        Company c = new Company();
        c.setParentId(company.getId());
        c.setCustomerId(company.getCustomerId());
        return companyMapper.selectCount(c) > 0 ;
    }

    private boolean hasUser(Company company){
        User user = new User();
        user.setCompanyId(company.getId());
        user.setCustomerId(company.getCustomerId());
        return userMapper.selectCount(user) > 0;
    }

}
